All files / src/components/admin CreateContentDialog.tsx

0% Statements 0/156
0% Branches 0/136
0% Functions 0/24
0% Lines 0/147

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
'use client';
 
import { useState, useEffect, useRef } from 'react';
import Image from 'next/image';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Search, AlertCircle, Film, Download, Loader2, Upload, X } from 'lucide-react';
import { useMediaUpload, formatFileSize } from '@/hooks/useMediaUpload';
import { Progress } from '@/components/ui/progress';
import { contentService, tmdbService } from '@/services';
import { useTranslation } from 'react-i18next';
import useLoadNamespace from '@/hooks/useLoadNamespace';
import { ContentType } from '@/types';
import { extractErrorMessage } from '@/lib/error-message';
import i18n from '@/lib/i18n';
 
const isValidVideoUrlOrPath = (value: string): boolean => {
  const trimmed = value.trim();
  if (!trimmed) return false;
  if (/^https?:\/\//i.test(trimmed)) return true;
  if (/^rtmps?:\/\//i.test(trimmed)) return true;
  if (trimmed.startsWith('/')) return true; // absolute Unix path or API path
  if (/^[a-zA-Z]:[\\/]/.test(trimmed)) return true; // Windows absolute path
  return false;
};
 
// Validation schema
const createContentSchema = z.object({
  title: z.string().min(1, i18n.t('manualSeries.titleRequired')),
  description: z.string().optional(),
  year: z.number().min(1900).max(new Date().getFullYear() + 5).optional(),
  poster_url: z.string().url(i18n.t('errors.invalidData')).optional().or(z.literal('')),
  backdrop_url: z.string().url(i18n.t('errors.invalidData')).optional().or(z.literal('')),
  video_url: z
    .string()
    .min(1, i18n.t('seriesManagement.videoUrlRequired'))
    .refine(isValidVideoUrlOrPath, i18n.t('errors.invalidData')),
  tmdb_id: z.number().optional(),
  active: z.boolean(),
  // TV Channel specific fields
  channel_number: z.number().min(1).optional(),
  provider: z.string().optional(),
  country: z.string().optional(),
  format: z.enum(['DRM', 'M3U8']).optional(),
  drm_keys: z.string().optional(),
  // LiveTV specific headers
  origin: z.string().url(i18n.t('errors.invalidData')).optional().or(z.literal('')),
  user_agent: z.string().optional(),
  referer: z.string().url(i18n.t('errors.invalidData')).optional().or(z.literal('')),
  custom_headers: z.string().optional()});
 
type CreateContentData = {
  title: string;
  description?: string;
  year?: number;
  poster_url?: string;
  backdrop_url?: string;
  video_url: string;
  tmdb_id?: number;
  active: boolean;
  // TV Channel specific fields
  channel_number?: number;
  provider?: string;
  country?: string;
  format?: 'DRM' | 'M3U8';
  drm_keys?: string;
  // LiveTV specific headers
  origin?: string;
  user_agent?: string;
  referer?: string;
  custom_headers?: string;
};
 
interface TMDBResult {
  id: number;
  title: string;
  overview?: string;
  release_date?: string;
  poster_url?: string;
  backdrop_url?: string;
  vote_average?: number;
  media_type?: string;
  year?: number;
}
 
interface CreateContentDialogProps {
  isOpen: boolean;
  onClose: () => void;
  contentType: ContentType;
  onSuccess: () => void;
}
 
export default function CreateContentDialog({
  isOpen,
  onClose,
  contentType,
  onSuccess}: CreateContentDialogProps) {
  const nsLoading = useLoadNamespace('admin/createContent');
 
  const { t } = useTranslation(['admin/createContent', 'admin', 'translation']);
 
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedTMDBItem, setSelectedTMDBItem] = useState<TMDBResult | null>(null);
  const [activeTab, setActiveTab] = useState<'tmdb' | 'manual'>(contentType === ContentType.TV ? 'manual' : 'tmdb');
  const [pendingSubtitleFile, setPendingSubtitleFile] = useState<File | null>(null);
  const [subtitleLanguage, setSubtitleLanguage] = useState('en');
 
  // Media upload
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { uploadFile, progress: uploadProgress, isUploading: isUploadingMedia, error: uploadError, cancelUpload } = useMediaUpload();
 
  // Map content type to category for upload
  const getCategoryForUpload = (): string => {
    switch (contentType) {
      case ContentType.VOD: return 'vod';
      case ContentType.SERIES: return 'series';
      case ContentType.KIDS: return 'kids';
      case ContentType.ANIME: return 'anime';
      case ContentType.EVENTS: return 'events';
      default: return 'vod';
    }
  };
 
  // Handle file selection for upload
  const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
 
    try {
      const category = getCategoryForUpload();
      const tmdbId = form.getValues('tmdb_id');
      const title = form.getValues('title') || file.name;
 
      const result = await uploadFile(file, category, tmdbId, title);
 
      // Set the video URL to the uploaded file's URL
      form.setValue('video_url', result.path ?? result.url, { shouldValidate: true });
    } catch (error) {
      // Error is already handled by the hook
      console.error('Upload failed:', error);
    }
 
    // Reset file input
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };
 
  const form = useForm<CreateContentData>({
    resolver: zodResolver(createContentSchema),
    defaultValues: {
      title: '',
      description: '',
      year: undefined,
      poster_url: '',
      backdrop_url: '',
      video_url: '',
      tmdb_id: undefined,
      active: true,
      // TV Channel specific fields
      channel_number: undefined,
      provider: '',
      country: '',
      format: undefined,
      drm_keys: '',
      // LiveTV specific headers
      origin: '',
      user_agent: '',
      referer: '',
      custom_headers: ''}});
 
  // TMDB search query
  const { data: tmdbResults, isLoading: isSearching, error: searchError, refetch: refetchSearch } = useQuery({
    queryKey: ['tmdb-search', searchQuery, contentType],
    queryFn: async () => {
      if (!searchQuery.trim()) return [];
 
      const result = await tmdbService.searchContent(searchQuery, contentType);
      if (result.success) {
        return result.data;
      }
      throw new Error(extractErrorMessage(result.error, t('common.serverError')));
    },
    enabled: !!searchQuery.trim() && activeTab === 'tmdb'});
 
  // Create content mutation
  const createContentMutation = useMutation({
    mutationFn: async (data: CreateContentData) => {
      let result;
 
      // Use specialized endpoints for Kids and Anime
      if (contentType === ContentType.KIDS) {
        const kidsData = {
          title: data.title,
          description: data.description,
          image_url: data.poster_url,
          stream_url: data.video_url,
          tmdb_id: data.tmdb_id,
          year: data.year};
        result = await contentService.createKidsContent(kidsData);
      } else if (contentType === ContentType.ANIME) {
        const animeData = {
          title: data.title,
          description: data.description,
          image_url: data.poster_url,
          stream_url: data.video_url,
          tmdb_id: data.tmdb_id,
          year: data.year};
        result = await contentService.createAnimeContent(animeData);
      } else if (contentType === ContentType.TV) {
        // Use specialized endpoint for TV Channels with Live TV fields
        const tvData = {
          name: data.title, // Note: API expects 'name' not 'title'
          description: data.description,
          logo_url: data.poster_url, // Note: API expects 'logo_url' not 'image_url'
          stream_url: data.video_url,
          channel_number: data.channel_number,
          provider: data.provider,
          country: data.country,
          format: data.format,
          drm_keys: data.drm_keys,
          origin: data.origin,
          user_agent: data.user_agent,
          referer: data.referer,
          custom_headers: data.custom_headers,
          active: data.active,
          is_live: true, // TV channels are always live
        };
        result = await contentService.createTVChannel(tvData);
      } else {
        const genericData = {
          ...data,
          type: contentType};
        result = await contentService.createContent(genericData);
      }
 
      if (result.success) {
        const createdContent = result.data as any;
        const createdContentId = Number(createdContent?.id);
        const supportsSubtitleUpload = [
          ContentType.VOD,
          ContentType.SERIES,
          ContentType.KIDS,
          ContentType.ANIME
        ].includes(contentType);
 
        if (pendingSubtitleFile && supportsSubtitleUpload) {
          if (!Number.isFinite(createdContentId) || createdContentId <= 0) {
            throw new Error(t('common.serverError'));
          }
 
          const subtitleUploadResult = await contentService.uploadContentSubtitle(
            createdContentId,
            pendingSubtitleFile,
            (subtitleLanguage || 'en').trim().toLowerCase()
          );
 
          if (!subtitleUploadResult.success) {
            throw new Error(extractErrorMessage(subtitleUploadResult.error, t('common.serverError')));
          }
        }
 
        return result.data;
      }
      throw new Error(extractErrorMessage(result.error, t('common.serverError')));
    },
    onSuccess: () => {
      onSuccess();
      form.reset();
      setSelectedTMDBItem(null);
      setSearchQuery('');
      setPendingSubtitleFile(null);
      setSubtitleLanguage('en');
    }});
 
  // Load TMDB details when item is selected
  const loadTMDBDetails = async (item: TMDBResult) => {
    setSelectedTMDBItem(item);
 
    // Auto-fill form with TMDB data
    form.setValue('title', item.title);
    form.setValue('description', item.overview || '');
    form.setValue('year', item.year || new Date(item.release_date || '').getFullYear());
    form.setValue('tmdb_id', item.id);
 
    if (item.poster_url) {
      form.setValue('poster_url', item.poster_url);
    }
    if (item.backdrop_url) {
      form.setValue('backdrop_url', item.backdrop_url);
    }
  };
 
  const handleSearch = () => {
    if (searchQuery.trim()) {
      // The search will be triggered automatically by the useQuery when searchQuery changes
      // We just need to refetch if needed
      refetchSearch();
    }
  };
 
  const handleSubmit = (data: CreateContentData) => {
    // Validate required fields
    if (!data.title?.trim() || !data.video_url?.trim()) {
      return;
    }
 
    createContentMutation.mutate(data);
  };
 
  // Reset form only when the dialog closes to avoid update loops
  useEffect(() => {
    if (!isOpen) {
      form.reset();
      setSelectedTMDBItem(null);
      setSearchQuery('');
      setActiveTab(contentType === ContentType.TV ? 'manual' : 'tmdb');
      setPendingSubtitleFile(null);
      setSubtitleLanguage('en');
    }
    // Depend only on `isOpen` and `contentType` (form is stable)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen, contentType]);
 
  const getContentTypeLabel = () => {
    switch (contentType) {
      case ContentType.VOD:
        return t('contentType.movie');
      case ContentType.TV:
        return t('contentType.tvChannel');
      case ContentType.SERIES:
        return t('contentType.tvSeries');
      case ContentType.EVENTS:
        return t('contentType.event');
      case ContentType.KIDS:
        return t('contentType.kidsContent');
      case ContentType.ANIME:
        return t('contentType.anime');
      default:
        return t('contentType.content');
    }
  };
 
  if (isOpen && nsLoading) {
    return (
      <Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose(); }}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t('common.loading')}</DialogTitle>
            <DialogDescription>{t('common.loading')}</DialogDescription>
          </DialogHeader>
        </DialogContent>
      </Dialog>
    );
  }
 
  return (
    <Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose(); }}>
      <DialogContent className="!max-w-[65vw] !w-[65vw] max-h-[75vh] overflow-y-auto sm:!max-w-[65vw] md:!max-w-[65vw] lg:!max-w-[65vw]" style={{ width: '65vw', maxWidth: '65vw' }}>
        <DialogHeader>
          <DialogTitle>{t('createContent.addNew', { type: getContentTypeLabel() })}</DialogTitle>
          <DialogDescription>
            {t('createContent.dialogDescription')}
          </DialogDescription>
        </DialogHeader>
 
        <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'tmdb' | 'manual')}>
          <TabsList className={`grid w-full h-12 bg-gray-100 p-1 ${contentType === ContentType.TV ? 'grid-cols-1' : 'grid-cols-2'}`}>
            {contentType !== ContentType.TV && (
              <TabsTrigger
                value="tmdb"
                className="flex items-center gap-2 h-10 data-[state=active]:bg-white data-[state=active]:shadow-sm"
              >
                <Search className="h-4 w-4" />
                {t('createContent.tmdbSearch')}
              </TabsTrigger>
            )}
            <TabsTrigger
              value="manual"
              className="flex items-center gap-2 h-10 data-[state=active]:bg-white data-[state=active]:shadow-sm"
            >
              <Film className="h-4 w-4" />
              {t('createContent.manualEntry')}
            </TabsTrigger>
          </TabsList>
 
          <TabsContent value="tmdb" className="space-y-6">
            <div className="relative">
              <div className="flex gap-3">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder={t('createContent.searchPlaceholder', { type: getContentTypeLabel().toLowerCase() })}
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                    className="pl-10 h-12 text-base border-2 focus:border-primary transition-colors"
                  />
                </div>
                <Button
                  onClick={handleSearch}
                  disabled={isSearching || !searchQuery.trim()}
                  className="h-12 px-8 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-medium"
                >
                  {isSearching ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      {t('createContent.searching')}
                    </>
                  ) : (
                    t('createContent.searchTmdb')
                  )}
                </Button>
              </div>
            </div>
 
            {searchError && (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>
                  {t('createContent.searchFailed')}: {searchError.message}
                </AlertDescription>
              </Alert>
            )}
 
            {isSearching && (
              <div className="flex flex-col items-center justify-center py-12 bg-gradient-to-br from-blue-50 to-purple-50 rounded-lg border">
                <div className="relative">
                  <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
                  <div className="absolute inset-0 h-8 w-8 rounded-full border-2 border-blue-200 animate-pulse"></div>
                </div>
                <p className="mt-4 text-lg font-medium text-gray-900">{t('createContent.searchingTmdb')}</p>
                <p className="text-sm text-gray-600 mt-1">{t('createContent.findingMatches', { query: searchQuery })}</p>
              </div>
            )}
 
            {tmdbResults && tmdbResults.length > 0 && (
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-semibold text-gray-900">{t('createContent.searchResults')}</h3>
                  <Badge variant="outline" className="text-sm">
                    {t('createContent.resultsFound', { count: tmdbResults.length })}
                  </Badge>
                </div>
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 max-h-[500px] overflow-y-auto pr-2 space-y-0">
                  {tmdbResults.map((item) => (
                    <Card
                      key={item.id}
                      className={`cursor-pointer transition-all duration-200 hover:shadow-lg border-2 ${selectedTMDBItem?.id === item.id
                        ? 'ring-2 ring-blue-500 border-blue-200 bg-blue-50'
                        : 'hover:border-gray-300 hover:bg-gray-50'
                        }`}
                      onClick={() => loadTMDBDetails(item)}
                    >
                      <CardContent className="p-4">
                        <div className="flex gap-4">
                          <div className="flex-shrink-0">
                            {item.poster_url ? (
                              <Image
                                src={item.poster_url.replace('w500', 'w154')}
                                alt={item.title}
                                width={80}
                                height={112}
                                className="w-20 h-28 object-cover rounded-lg shadow-md"
                              />
                            ) : (
                              <div className="w-20 h-28 bg-gray-200 rounded-lg flex items-center justify-center">
                                <Film className="h-8 w-8 text-gray-400" />
                              </div>
                            )}
                          </div>
                          <div className="flex-1 min-w-0 space-y-2">
                            <div>
                              <h4 className="font-semibold text-gray-900 truncate text-base">
                                {item.title}
                              </h4>
                              <div className="flex items-center gap-2 mt-1">
                                <Badge variant="outline" className="text-xs">
                                  {item.year || new Date(item.release_date || '').getFullYear() || t('createContent.unknownYear')}
                                </Badge>
                                <Badge variant="secondary" className="text-xs">
                                  {item.media_type === 'movie' ? t('contentType.movie') : t('contentType.tvShow')}
                                </Badge>
                              </div>
                            </div>
                            <p className="text-sm text-gray-600 line-clamp-3 leading-relaxed">
                              {item.overview || t('createContent.noDescription')}
                            </p>
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-1">
                                <span className="text-yellow-500">⭐</span>
                                <span className="text-sm font-medium">
                                  {item.vote_average?.toFixed(1) || t('common.notAvailable')}
                                </span>
                              </div>
                              <Badge variant="outline" className="text-xs">
                                {t('createContent.idLabel', { id: item.id })}
                              </Badge>
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </div>
            )}
 
            {searchQuery && tmdbResults && tmdbResults.length === 0 && !isSearching && (
              <div className="text-center py-12 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
                <div className="max-w-sm mx-auto">
                  <Film className="h-16 w-16 text-gray-400 mx-auto mb-4" />
                  <h3 className="text-lg font-medium text-gray-900 mb-2">{t('createContent.noResultsFound')}</h3>
                  <p className="text-gray-600 mb-4">
                    {t('createContent.noResultsDescription', { type: getContentTypeLabel().toLowerCase(), query: searchQuery })}
                  </p>
                  <div className="space-y-2 text-sm text-gray-500 mb-4">
                    <p>• {t('createContent.suggestions.tryKeywords')}</p>
                    <p>• {t('createContent.suggestions.checkSpelling')}</p>
                    <p>• {t('createContent.suggestions.useOriginalTitle')}</p>
                  </div>
                  <Button
                    variant="outline"
                    className="mt-2"
                    onClick={() => setActiveTab('manual')}
                  >
                    {t('createContent.switchToManual')}
                  </Button>
                </div>
              </div>
            )}
          </TabsContent>
 
          <TabsContent value="manual">
            <Alert>
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                {t('createContent.manualAlert')}
              </AlertDescription>
            </Alert>
          </TabsContent>
        </Tabs>
 
        {/* Content Form */}
        <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="title">{t('createContent.labels.title')} *</Label>
              <Input
                id="title"
                {...form.register('title')}
                placeholder={t('createContent.form.titlePlaceholder')}
              />
              {form.formState.errors.title && (
                <p className="text-sm text-red-600 mt-1">
                  {form.formState.errors.title.message}
                </p>
              )}
            </div>
            <div>
              <Label htmlFor="year">{t('createContent.labels.year')}</Label>
              <Input
                id="year"
                type="number"
                min="1900"
                max={new Date().getFullYear() + 5}
                {...form.register('year', {
                  valueAsNumber: true,
                  setValueAs: (value) => value === '' ? undefined : Number(value)
                })}
                placeholder={t('createContent.form.yearPlaceholder')}
              />
              {form.formState.errors.year && (
                <p className="text-sm text-red-600 mt-1">
                  {form.formState.errors.year.message}
                </p>
              )}
            </div>
          </div>
 
          <div>
            <Label htmlFor="description">{t('createContent.labels.description')}</Label>
            <Textarea
              id="description"
              {...form.register('description')}
              placeholder={t('createContent.form.descriptionPlaceholder')}
              rows={3}
            />
          </div>
 
          <div>
            <Label htmlFor="video_url">{t('createContent.labels.videoUrl')} *</Label>
            <div className="relative">
              <Input
                id="video_url"
                {...form.register('video_url')}
                placeholder={t('createContent.form.videoUrlPlaceholder')}
                className="pr-12"
                disabled={isUploadingMedia}
              />
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                disabled={isUploadingMedia}
                className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-md hover:bg-gray-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                title={t('createContent.uploadVideo')}
              >
                <Upload className="h-5 w-5 text-gray-500 hover:text-blue-600" />
              </button>
              <input
                type="file"
                ref={fileInputRef}
                accept="video/*,.mp4,.mkv,.avi,.mov,.webm,.m4v,.ts"
                onChange={handleFileSelect}
                className="hidden"
              />
            </div>
            {uploadProgress && (
              <div className="mt-2 space-y-1">
                <div className="flex items-center justify-between text-xs text-gray-600">
                  <span>{t('createContent.uploading')} {uploadProgress.percentage}%</span>
                  <button
                    type="button"
                    onClick={cancelUpload}
                    className="text-red-500 hover:text-red-700"
                  >
                    <X className="h-4 w-4" />
                  </button>
                </div>
                <Progress value={uploadProgress.percentage} className="h-2" />
                <span className="text-xs text-gray-500">
                  {formatFileSize(uploadProgress.loaded)} / {formatFileSize(uploadProgress.total)}
                </span>
              </div>
            )}
            {uploadError && (
              <p className="text-sm text-red-600 mt-1">{uploadError}</p>
            )}
            {form.formState.errors.video_url && !uploadError && (
              <p className="text-sm text-red-600 mt-1">
                {form.formState.errors.video_url.message}
              </p>
            )}
          </div>
 
          {contentType !== ContentType.TV && contentType !== ContentType.EVENTS && (
            <div className="rounded-md border p-3 bg-muted/20 space-y-3">
              <Label className="text-sm font-medium">
                {t('manualSeries.subtitlesTitle', { ns: 'translation' })}
              </Label>
              <div className="grid grid-cols-1 md:grid-cols-[110px_1fr] gap-2 items-end">
                <div>
                  <Label htmlFor="subtitle_language" className="text-xs">
                    {t('common.language')}
                  </Label>
                  <Input
                    id="subtitle_language"
                    value={subtitleLanguage}
                    onChange={(e) => setSubtitleLanguage(e.target.value.trim().toLowerCase())}
                    placeholder={t('manualSeries.subtitleLanguagePlaceholder', { ns: 'translation' })}
                    maxLength={16}
                  />
                </div>
                <div>
                  <Label htmlFor="subtitle_file" className="text-xs">
                    {t('manualSeries.subtitleFile', { ns: 'translation' })}
                  </Label>
                  <Input
                    id="subtitle_file"
                    type="file"
                    accept=".srt,.vtt,text/vtt,application/x-subrip"
                    onChange={(e) => setPendingSubtitleFile(e.target.files?.[0] ?? null)}
                  />
                </div>
              </div>
            </div>
          )}
 
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="poster_url">{t('createContent.labels.posterUrl')}</Label>
              <Input
                id="poster_url"
                {...form.register('poster_url')}
                placeholder={t('createContent.form.posterUrlPlaceholder')}
              />
            </div>
            <div>
              <Label htmlFor="backdrop_url">{t('createContent.labels.backdropUrl')}</Label>
              <Input
                id="backdrop_url"
                {...form.register('backdrop_url')}
                placeholder={t('createContent.form.backdropUrlPlaceholder')}
              />
            </div>
          </div>
 
          {/* TV Channel specific fields - only show for TV content */}
          {contentType === ContentType.TV && (
            <>
              <div className="border-t pt-6">
                <h3 className="text-lg font-semibold mb-4">{t('createContent.tv.tvSettingsTitle')}</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="channel_number">{t('createContent.labels.channelNumber')}</Label>
                    <Input
                      id="channel_number"
                      type="number"
                      {...form.register('channel_number', { valueAsNumber: true })}
                      placeholder={t('createContent.form.channelNumberPlaceholder')}
                    />
                  </div>
                  <div>
                    <Label htmlFor="provider">{t('createContent.labels.provider')}</Label>
                    <Input
                      id="provider"
                      {...form.register('provider')}
                      placeholder={t('createContent.form.providerPlaceholder')}
                    />
                  </div>
                  <div>
                    <Label htmlFor="country">{t('createContent.labels.country')}</Label>
                    <Input
                      id="country"
                      {...form.register('country')}
                      placeholder={t('createContent.form.countryPlaceholder')}
                    />
                  </div>
                  <div>
                    <Label htmlFor="format">{t('createContent.labels.format')}</Label>
                    <select
                      id="format"
                      {...form.register('format')}
                      className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      <option value="">{t('createContent.form.formatSelectPlaceholder')}</option>
                      <option value="M3U8">{t('createContent.form.formatOption.m3u8')}</option>
                      <option value="DRM">{t('createContent.form.formatOption.drm')}</option>
                    </select>
                  </div>
                </div>
 
                {form.watch('format') === 'DRM' && (
                  <div className="mt-4">
                    <Label htmlFor="drm_keys">{t('createContent.labels.drmKeys')}</Label>
                    <Textarea
                      id="drm_keys"
                      {...form.register('drm_keys')}
                      placeholder={t('createContent.form.drmPlaceholder')}
                      rows={3}
                      className="font-mono text-sm"
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      {t('createContent.tv.drmFormatNote')}
                    </p>
                  </div>
                )}
              </div>
 
              <div className="border-t pt-6">
                <h3 className="text-lg font-semibold mb-4">{t('createContent.tv.liveTvTitle')}</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="origin">{t('createContent.labels.origin')}</Label>
                    <Input
                      id="origin"
                      {...form.register('origin')}
                      placeholder={t('createContent.form.originPlaceholder')}
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      {t('createContent.tv.originNote')}
                    </p>
                  </div>
                  <div>
                    <Label htmlFor="user_agent">{t('createContent.labels.userAgent')}</Label>
                    <Input
                      id="user_agent"
                      {...form.register('user_agent')}
                      placeholder={t('createContent.form.userAgentPlaceholder')}
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      {t('createContent.tv.userAgentNote')}
                    </p>
                  </div>
                  <div>
                    <Label htmlFor="referer">{t('createContent.labels.referer')}</Label>
                    <Input
                      id="referer"
                      {...form.register('referer')}
                      placeholder={t('createContent.form.refererPlaceholder')}
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      {t('createContent.tv.refererNote')}
                    </p>
                  </div>
                  <div>
                    <Label htmlFor="custom_headers">{t('createContent.labels.customHeaders')}</Label>
                    <Textarea
                      id="custom_headers"
                      {...form.register('custom_headers')}
                      placeholder={t('createContent.form.customHeadersPlaceholder')}
                      rows={3}
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      {t('createContent.tv.customHeadersNote')}
                    </p>
                  </div>
                </div>
              </div>
            </>
          )}
 
          {selectedTMDBItem && (
            <Alert>
              <Download className="h-4 w-4" />
              <AlertDescription>
                {t('createContent.metadataLoaded', { title: selectedTMDBItem.title, id: selectedTMDBItem.id })}
              </AlertDescription>
            </Alert>
          )}
 
          {createContentMutation.error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                {createContentMutation.error.message}
              </AlertDescription>
            </Alert>
          )}
 
          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>
              {t('common.cancel')}
            </Button>
            <Button
              type="submit"
              disabled={createContentMutation.isPending}
            >
              {createContentMutation.isPending ? t('createContent.creating') : t('createContent.createButton', { type: getContentTypeLabel() })}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}